//
//  BELookPackageController.swift
//  BEGlobalOiler
//
//  Created by KKING on 16/9/12.
//  Copyright © 2016年 Bullseye Energy pte ltd. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
import QuickLook
import Kingfisher

class BELookPackageController: UIViewController {
    
    var orderTalentId: String = "" {
        didSet{
            loadData(orderTalentId: orderTalentId)
        }
    }
    
    @IBOutlet weak var imgOne: UIImageView!
    @IBOutlet weak var imgTwo: UIImageView!
    @IBOutlet weak var imgThree: UIImageView!
    
    @IBOutlet weak var packageBtn: UIButton!
    @IBOutlet weak var approveBtn: UIButton!
    @IBOutlet weak var evaluateBtn: UIButton!
    
    
    @IBOutlet weak var orderStatusTF: UILabel!
    @IBOutlet weak var rigNameTF: UILabel!
    @IBOutlet weak var rigLocationTF: UILabel!
    @IBOutlet weak var expectStartTimeTF: UILabel!
    @IBOutlet weak var iconImgView: UIImageView!
    @IBOutlet weak var talentNameTF: UILabel!
    
    
    var phone: String = ""
    var talentName: String = ""
    
    private lazy var drawingboardView: BEDrawingboardView = {
        
        let drawingboard = BEDrawingboardView.drawingboardView() as! BEDrawingboardView
        drawingboard.frame = CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: 250)
        drawingboard.backgroundColor = UIColor.colorWithHexString(hex: "#ffffff")
        
        return drawingboard
    }()
    
    //查看工作报告
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        weak var weakSelf = self
        drawingboardView.ordertalentId = orderTalentId
        drawingboardView.dismissboardBlock = {
            () -> () in
            self.dismissKeyboard()
        }
        
        drawingboardView.changeimgHidBlock = {
            () -> () in
            weakSelf!.imgTwo.isHidden = false
            weakSelf!.evaluateBtn.isUserInteractionEnabled = true
            weakSelf!.evaluateBtn.alpha = 1
        }
    }
    
    private func loadData(orderTalentId: String){
        BENetworkTools.shareNetworkTool.loadOrderTalentData(ordertalentId: orderTalentId, finished: { (success, result, error) in
            
            guard let resultjson = result else {
                JFProgressHUD.showWithStatus(status: "Network fault!")
                return
            }
            if resultjson["success"] == true {
                guard let dict = resultjson["result"].dictionaryObject else{
                    return
                }
                let orderTalent = BEOrderTalentModel(dict: dict as [String : AnyObject])
                DispatchQueue.main.async(execute: {
                    self.setupUIData(orderTalent: orderTalent)
                })
                JFProgressHUD.showSuccessWithStatus(status: "Order confirmation success!")
            } else {
                JFProgressHUD.showInfoWithStatus(status: resultjson["message"].stringValue)
            }
        })
    }
    
    private func setupUIData(orderTalent: BEOrderTalentModel){
        orderStatusTF.text = orderTalent.statusName
        expectStartTimeTF.text = orderTalent.expectStartTime
        rigNameTF.text = orderTalent.rigName
        rigLocationTF.text = orderTalent.rigLocation
        talentNameTF.text = orderTalent.talentName

        guard let urlString = orderTalent.photo else {
            return
        }
        let url = URL(string: urlString)
        iconImgView.kf.setImage(with: url, placeholder: #imageLiteral(resourceName: "avatar_default_big"), options: [], progressBlock: nil, completionHandler: nil)

        phone = orderTalent.mobile!
        talentName = orderTalent.talentName!
    }
    
    
    private func setupUI(){
        
        NotificationCenter.default.addObserver(self, selector: #selector(BELookPackageController.changeImgHidNotification), name: NSNotification.Name(rawValue: ChangeImgHidNotification), object: nil)
        
        approveBtn.isUserInteractionEnabled = false
        approveBtn.alpha = 0.6
        
        evaluateBtn.isUserInteractionEnabled = false
        evaluateBtn.alpha = 0.6
        
        imgOne.isHidden = true
        imgTwo.isHidden = true
        imgThree.isHidden = true
    }
    
    @objc func changeImgHidNotification(){
        imgThree.isHidden = false
    }
    
    //移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    //查看报告按钮
    @IBAction func packageButtonClick(sender: UIButton) {
        //        let packageReadingVC = BEPackageReadingController()
        //        weak var weakSelf = self
        //        packageReadingVC.changeBtnStatuBlock = {
        //            () -> () in
        //            weakSelf!.approveBtn.isUserInteractionEnabled = true
        //            weakSelf!.approveBtn.alpha = 1
        //            weakSelf!.imgOne.isHidden = false
        //        }
        
        let preViewC : QLPreviewController = QLPreviewController()
        preViewC.dataSource = self
        preViewC.view.backgroundColor = COLOR_ALL_BG
        weak var weakSelf = self
        present(preViewC, animated: true) {
            weakSelf!.approveBtn.isUserInteractionEnabled = true
            weakSelf!.approveBtn.alpha = 1
            weakSelf!.imgOne.isHidden = false
        }
        //        navigationController?.pushViewController(preViewC, animated: true)
    }
    
    //签名按钮
    @IBAction func signatureConfirmClick(sender: UIButton) {
        tabBarController?.view.addSubview(drawingboardView)
        UIView.animate(withDuration: 0.3) {
            self.drawingboardView.y = SCREEN_HEIGHT - self.drawingboardView.height
        }
    }
    
    
    //评价工人按钮点击
    @IBAction func evaluateTechClick(sender: AnyObject) {
        let evaluateTechVC = BEEvaluateController()
        evaluateTechVC.talentName = talentName
        evaluateTechVC.ordertalentId = orderTalentId
        //层级较深 此处选择使用通知
        navigationController?.pushViewController(evaluateTechVC, animated: true)
    }
    
    
    
    @IBAction func callHimButtonDidClick(sender: UIButton) {
        let alertVC = UIAlertController(title: "CALL", message: "确定要呼叫"+"\(phone)"+"吗?", preferredStyle: .alert)
        
        let cancleAction = UIAlertAction(title: "Cancle", style: .cancel, handler: nil)
        let doneAction = UIAlertAction(title: "OK", style: .default) { (_) in
            
            let url = NSURL(string: "tel://\(self.phone)")
            UIApplication.shared.openURL(url! as URL)
        }
        
        alertVC.addAction(cancleAction)
        alertVC.addAction(doneAction)
        
        UIApplication.shared.keyWindow?.rootViewController!.present(alertVC, animated: true, completion: nil)
        
    }
    
    @IBAction func sendButtonDidClick(sender: UIButton) {
        let alertVC = UIAlertController(title: "IM尚未开放", message: nil, preferredStyle: .alert)
        let cancleAction = UIAlertAction(title: "Cancle", style: .cancel, handler: nil)
        let doneAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alertVC.addAction(cancleAction)
        alertVC.addAction(doneAction)
        
        UIApplication.shared.keyWindow?.rootViewController!.present(alertVC, animated: true, completion: nil)
    }
    
    @IBAction func lookJourneyButtonDidClick(sender: UIButton) {
        navigationController?.pushViewController(BELookJourneyController(), animated: true)
    }
    
    
    
    @objc func doneBtnDidClick(){
        //此处保存图片并上传 然后删掉键盘
        dismissKeyboard()
    }
    
    
    @objc func cancleBtnDidClick(){
        dismissKeyboard()
    }
    
    private func dismissKeyboard(){
        //        weak var weakSelf = self
        UIView.animate(withDuration: 0.3, animations: {
            self.drawingboardView.y = SCREEN_HEIGHT
        }) { (_) in
            self.drawingboardView.removeFromSuperview()
        }
    }
    
    
    func image(image: UIImage, didFinishSavingWithError: NSError?,contextInfo: AnyObject)
    {
        if didFinishSavingWithError != nil
        {
            JFProgressHUD.showErrorWithStatus(status: "保存失败,请稍候重试...")
            return
        }
        JFProgressHUD.showSuccessWithStatus(status: "图片保存成功!")
    }
}




extension BELookPackageController :  QLPreviewControllerDataSource{
    
    /// QLPreviewController 数据源方法
    ///
    /// - parameter controller: QLPreviewController控制器
    ///
    /// - returns: 返回页数
    func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
        return 1
    }
    func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
        return YJPreviewItem()
    }
}

/// 文件QLPreviewItem
class YJPreviewItem: NSObject, QLPreviewItem {
    
    var previewItemURL: URL? {
        return Bundle.main.url(forResource: "Test", withExtension: "pdf")
    }
    
    var previewItemTitle: String? {
        return "Service Package"
    }
}
